<template>
    <div class="login-body">
        <div class="login-panel">
            <div class="login-title">用户登录</div>
            <el-form :model="formData">
                <el-form-item prop="account" ref="loginForm" :rules="formRules.account">
                    <el-input placeholder="请输入账号" v-model="formData.account" size="large">
                        <template #prefix>
                            <span class="iconfont icon-Account"></span>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item prop="password" :rules="formRules.password">
                    <el-input type="password" placeholder="请输入密码" v-model="formData.password" size="large">
                        <template #prefix>
                            <span class="iconfont icon-password"></span>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item prop="checkCode" :rules="formRules.checkCode">
                    <el-input type="checkCode" placeholder="请输入验证码" v-model="formData.checkCode" size="large" :style="{ width: '70%' }">
                        <template #prefix>
                            <span class="iconfont icon-checkCode"></span>
                        </template>
                    </el-input>
                    <img :src="checkCodeUrl" alt="验证码" @click="refreshCheckCode" style="cursor: pointer; width: 30%">
                </el-form-item>

                <el-form-item label="">
                    <el-button type="primary" :style="{ width: '100%' }" @click="submitForm">登录</el-button>
                </el-form-item>
                <div class="container">
                   <!-- <div class="qq">
                        <span class="a-link" @click="showPhoneLoginForm">QQ登录<router-link to="/"></router-link></span>
                    </div>-->
                    <div class="phone">
                        <span class="a-link" @click="showPhoneLoginForm">手机号登录<router-link to="/"></router-link></span>
                    </div>
                </div>

                <!-- 显示错误消息 -->
                <div v-if="showErrorMessage" class="error-message">
                    {{errorMessage}}
                </div>
            </el-form>
        </div>
        <el-dialog v-model="phoneLoginFormVisible" title="手机号登录" :width="'30%'">
            <el-form :model="phoneLoginForm" label-width="80px" style="text-align: center;">
                <el-form-item label="手机号" prop="phone" :rules="phoneLoginRules.phone">
                    <el-input v-model="phoneLoginForm.phone" style="width: 50%;"></el-input>
                </el-form-item>
                <el-form-item label="验证码" prop="code">
                    <el-input v-model="phoneLoginForm.code" style="width: 50%;"></el-input>
                    <el-button  :disabled="countDown > 0" @click="sendVerificationCode">
                        <span v-if="countDown === 0">获取验证码</span>
                        <span v-else>{{ countDown }} 秒后重新获取</span>
                    </el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="codeLogin">登录</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>


    </div>
</template>
<script setup>
    import {ref} from 'vue';
    import axios from 'axios';
    import {useRouter} from 'vue-router'
    const countDown = ref(0);
    const router = useRouter();
    const formData = ref({
        account: '',
        password: '',
        checkCode:'',
    });
    const showErrorMessage = ref(false);
    const errorMessage=ref('');
    const formRules = {
        account: [{required: true, message: '请输入账号', trigger: 'blur'}],
        password: [{required: true, message: '请输入密码', trigger: 'blur'}],
        checkCode: [{required: true, message: '请输入验证码', trigger: 'blur'}],
    };
    const phoneLoginFormVisible = ref(false);
    const phoneLoginForm = ref({
        phone: '',
        code: '',
    });
    const phoneLoginRules={
        phone:[{required:true,message:'请输入手机号',trigger:'blur'}],
    }
    const codeCurrent=ref("")
    //验证码图片获取
    const checkCodeUrl = ref('http://localhost:8080/user/checkCode'); // 后端获取验证码图片的接口地址
    let lastSendTime = 0;
    const refreshCheckCode = () => {
        // 刷新验证码
        checkCodeUrl.value = 'http://localhost:8080/user/checkCode?' + new Date().getTime();
    };
    //发送验证码
    const sendVerificationCode=()=> {
        if (phoneLoginForm.value.phone != null) {
            axios.get('http://localhost:8080/user/phoneCode')
                .then((response) => {
                    console.log(response.data.data);
                    codeCurrent.value = response.data.data;
                })
        };
        //获取手机验证码
        const currentTime = Date.now();
        if (currentTime - lastSendTime < 60000) { // 检查与上一次发送时间的时间差是否小于 60 秒
            alert('请在 60 秒后再次发送验证码');
        }
    }
    // 页面加载时获取验证码
    refreshCheckCode();
    const submitForm = () => {
        // 使用axios发送POST请求到后端接口
        console.log('Account:', formData.value.account);
        console.log('Password:', formData.value.password);
        console.log('Password:', formData.value.checkCode);
        // 重置错误消息
        showErrorMessage.value = false;

        // 修改Axios请求，将返回的数据直接传递给前端处理
        axios.post('http://localhost:8080/user/login', formData.value)
            .then((response) => {
                console.log('Login response:', response.data);
                if (response.data.code === 1) {
                    // 假设JWT令牌在响应的data字段中
                    const jwtToken = response.data.data;// 假设你已经生成了JWT令牌 jwtToken
                    localStorage.setItem('jwtToken', jwtToken);
                    console.log(jwtToken+"66666666666666666666666666666")

                    showErrorMessage.value = false;
                    alert("登录成功");
                    if (jwtToken) {
                        // 解码JWT令牌（假设它是一个包含用户名的 JSON）
                        const tokenData = JSON.parse(decodeURIComponent(escape(atob(jwtToken.split('.')[1]))));
                        console.log('Token Data:', tokenData.token.tokenValue);
                        // 设置用户名
                    }
                    router.push("/homePage");
                } else {
                    showErrorMessage.value = true;
                    if(response.data.msg=="验证码错误"){
                        errorMessage.value = "验证码错误";
                    }else if(response.data.msg=="用户名或密码错误"){
                        errorMessage.value = "用户名或密码错误";
                    }
                }
            })
            .catch((error) => {
                console.error('Login error:', error);
            });
    };
    //手机号登录
    const showPhoneLoginForm = () => {
        phoneLoginFormVisible.value = true;
    };
    //验证码登录
    const codeLogin = ()=> {
        console.log(phoneLoginForm.value.code);
        if(codeCurrent.value==phoneLoginForm.value.code){
            console.log('成功')
            // 修改Axios请求，将返回的数据直接传递给前端处理
            axios.get(`http://localhost:8080/user/phoneLogin/${phoneLoginForm.value.phone}`)
                .then((response) => {
                    console.log('Login response:', response.data);
                    if (response.data.code === 1) {
                        // 假设JWT令牌在响应的data字段中
                        const jwtToken = response.data.data;// 假设你已经生成了JWT令牌 jwtToken
                        localStorage.setItem('jwtToken', jwtToken);
                        showErrorMessage.value = false;
                        alert("登录成功");
                        router.push("/homePage");
                    } else {
                        showErrorMessage.value = true;
                    }
                })
                .catch((error) => {
                    console.error('Login error:', error);
                });
        }else{
            alert("验证码错误"); // 在这里添加代码来显示提示消息或者弹框
        }
    };

</script>
<style lang='scss'>
    .login-body {
        width: 100%;
        height: calc(100vh);
        background-image: url(../assets/100.png);
        background-size: 100% 100%;
        background-position: center;

        .login-panel {
            margin-top: 250px;
            float: right;
            margin-right: 150px;
            padding: 20px;
            width: 350px;
            background-color: rgba(255, 255, 255, 0.8);
            border-radius: 5px;
            box-shadow: 2px 2px 10px #dddd;

            .login-title {
                font-size: 24px;
                text-align: center;
                margin-bottom: 10px;
            }

            .check-code-panel {
                display: flex;

                .input-panel {
                    flex: 1;
                    margin-right: 5px;
                }
            }
            .container {
                display: flex;
                justify-content: space-between; /* 将元素之间的空间均匀分配 */
                align-items: center; /* 垂直居中对齐 */
            }

            .phone {
                font-size: 14px;
                text-align: right;
                margin-bottom: 0px;
            }

            .qq {
                font-size: 14px;
                text-align: left;
                margin-left: 5px;
            }


            .error-message {
                color: #ff0000;
                margin-top: 10px;
            }
        }
    }
</style>